<?php

/**
 * AnnouncementController
 * 
 * @author
 */

require_once 'Zend/Controller/Action.php';

class AnnouncementController extends Zend_Controller_Action 
{
	protected $_announcementModel;
	
	public function init()
	{
		$this->_announcementModel = new Eleven_Model_Announcement();
		
		$this->view->postForm = $this->getPostForm();
	}
	
	/**
	 * The default action - show the home page
	 */
	public function indexAction() {
		$announcements = $this->_announcementModel->getAnnouncements ( $this->_getParam ( 'page', 1 ), array ('publishdate DESC' ) );
		
		$this->view->assign(array('announcements'=>$announcements));
	}
	
	public function viewAction()
	{
		$announcement = $this->_announcementModel
				->getAnnounceById($this->_getParam('announcementId'));
        
        if (null === $announcement) {
            throw new CMS_Exception_404('未知的文档， Announcement文档Id为 ' . $this->_getParam('announcementId'));
        }else{
        	$announcement->views++;
        	$announcement->save();
        }
        
        $this->view->assign(array(
            'announcement' => $announcement,
            )
        );
	}
	
	public function postAction()
	{
	    if (!$this->_announcementModel->checkAcl('post')) {
            return $this->_helper->redirector('index','announcement');
        }
	}
	
	public function saveAction()
	{
	 if (!$this->_announcementModel->checkAcl('save')) {
            return $this->_helper->redirector('index','announcement');
        }
        
		$request = $this->getRequest();
		if (!$request->isPost()) 
		{
			return $this->_helper->redirector('index');
  		}
  		
  		if (false === $this->_announcementModel->savePost($request->getPost())) 
  		{
     		return $this->render('post');
  		}
  		
  		return $this->_helper->redirector('index');
	}
	
	public function getPostForm()
	{
		$urlHelper = $this->_helper->getHelper('url');

        $this->_forms['post'] = $this->_announcementModel->getForm('announcementPost');
        $this->_forms['post']->setAction($urlHelper->url(array(
            'action' => 'save'
            ),
            'default'
        ));
        
        $this->_forms['post']->setMethod('post');

        return $this->_forms['post'];
	}

}

